package com.hd.controller.sys;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.hd.commons.annotation.LogAnnotation;
import com.hd.entity.enums.OperatorTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hd.controller.base.BaseController;
import com.hd.entity.sys.Role;
import com.hd.service.sys.RoleService;
import com.hd.util.StringUtils;
import com.hd.util.result.PageInfo;

/**
 * <p>
 * 前端控制器:角色
 * </p>
 */
@RequestMapping("role")
@Controller
public class RoleController extends BaseController {
    @Autowired
    private RoleService roleService;

    @RequestMapping("manager")
    public String manager() {
        return "jsp/sys/role/roleList";
    }

    /**
     * 角色列表
     *
     * @param page
     * @param rows
     * @param sort
     * @param order
     * @return
     */
    @RequestMapping(value = "/dataGrid", method = RequestMethod.POST)
    @ResponseBody
    public Object dataGrid(Role role, Integer page, Integer rows, String sort, String order) {
        PageInfo pageInfo = new PageInfo(page, rows, sort, order);
        Map<String, Object> condition = new HashMap<String, Object>();
        if (StringUtils.isNotNull(role.getName())) {
            condition.put("name", role.getName());
        }

        pageInfo.setCondition(condition);
        roleService.selectDataGrid(pageInfo);
        return pageInfo;
    }

    /**
     * 权限树
     *
     * @return
     */
//    @RequestMapping(value = "/tree", method = RequestMethod.POST)
//    @ResponseBody
//    public Object tree() {
//        return roleService.selectTree();
//    }

    /**
     * 添加角色页
     *
     * @return
     */
    @RequestMapping("/addPage")
    public String addPage() {
        return "jsp/sys/role/roleAdd";
    }

    /**
     * 添加角色
     *
     * @param role
     * @return
     */
    @LogAnnotation(value = "添加角色",method = OperatorTypeEnum.SAVE)
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Object add(Role role) {
        if (role.getName() == null || role.getName().trim().equals("")) {
            return renderError("角色名不能为空！");
        }
        Role vo = roleService.findbyName(role.getName());
        if (vo != null) {
            return renderError("角色名已存在！");
        }
        //校验角色编码是否正确
        String msg = validRoleCode(role.getCode(), "");
        if (StringUtils.isNotNull(msg)) {
            return renderError(msg);
        }

        if (vo == null) {
            role.setId(UUID.randomUUID().toString());
            roleService.insert(role);
            return renderSuccess("添加成功！");
        } else {
            return renderError("角色名已存在！");
        }
    }

    /**
     * 校验角色编码是否正确
     *
     * @param roleCode
     * @return
     */
    public String validRoleCode(String roleCode, String oldRoleCode) {
        String msg = "";
        if (StringUtils.isNull(roleCode)) {
            msg = "角色编码不能为空";
        } else {
            if (!roleCode.startsWith("ROLE_")) {
                msg = "角色编码必须以ROLE_开头";
            } else {
                if (!roleCode.equals(oldRoleCode)) {
                    Role role = roleService.findbyCode(roleCode);
                    if (role != null) {
                        msg = "角色编码已存在";
                    }
                }
            }
        }
        return msg;
    }

    /**
     * 删除角色
     *
     * @param id
     * @return
     */
    @LogAnnotation("删除角色")
    @RequestMapping("/delete")
    @ResponseBody
    public Object delete(String id) {
        Role vo = roleService.selectById(id);
        if (!vo.getName().equals("admin")) {
            roleService.deleteById(id);
            return renderSuccess("删除成功！");
        } else {
            return renderError("你没有删除超级管理员的权限！");
        }
    }

    /**
     * 编辑角色页
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/editPage")
    public String editPage(Model model, String id) {
        Role role = roleService.selectById(id);
        model.addAttribute("role", role);
        return "jsp/sys/role/roleEdit";
    }

    /**
     * 编辑角色
     *
     * @param role
     * @return
     */
    @RequestMapping("/edit")
    @ResponseBody
    public Object edit(Role role) {
        if (StringUtils.isNull(role.getName())) {
            return renderError("角色名不能为空");
        }

        // 判断角色名是否已存在
        Role vo = roleService.selectById(role.getId());
        if (!vo.getName().equals(role.getName())) {
            Role r = roleService.findbyName(role.getName());
            if (r != null) {
                return renderError("角色名已存在");
            }
        }
        // 校验角色编码是否正确
        String msg = validRoleCode(role.getCode(), vo.getCode());
        if (StringUtils.isNotBlank(msg)) {
            return renderError(msg);
        }
        roleService.updateById(role);
        Role vvo = roleService.selectById(role.getId());
        if (!vvo.getName().equals("admin")) {
            roleService.updateById(role);
            return renderSuccess("编辑成功！");
        } else {
            return renderError("你没有编辑超级管理员的权限！");
        }
    }

    /**
     * 授权页面
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/grantPage")
    public String grantPage(Model model, String id) {
        model.addAttribute("id", id);
        return "jsp/sys/role/roleGrant";
    }

    /**
     * 授权页面页面根据角色查询资源
     *
     * @param id
     * @return
     */
    @RequestMapping("/findResourceIdListByRoleId")
    @ResponseBody
    public Object findResourceByRoleId(String id) {
        List<String> resources = roleService.selectResourceIdListByRoleId(id);
        return renderSuccess(resources);
    }

    /**
     * 授权
     *
     * @param id
     * @param resourceIds
     * @return
     */
    @RequestMapping("/grant")
    @ResponseBody
    public Object grant(String id, String resourceIds) {
        roleService.updateRoleResource(id, resourceIds);
        return renderSuccess("授权成功！");
    }

    /**
     * 角色选择页面
     *
     * @param roleids
     * @param flag=flase|true 多选 |单选
     * @return
     */
    @RequestMapping("/roleSelect")
    public String roleSelect(String roleids, Boolean flag, Model model) {
        model.addAttribute("roleids", roleids);
        model.addAttribute("flag", flag);
        return "jsp/sys/role/roleSelect";
    }

    @ResponseBody
    @RequestMapping("/synRoleToActiviti")
    public Object synRoleToActiviti() throws Exception {
        roleService.synRoleToActiviti();
        return renderSuccess("同步角色成功！");
    }
}
